package com.googlecode.adaboost.classifier.point;

import java.util.Map;
import java.util.Vector;

import com.googlecode.adaboost.classifier.RealWeakClassifier;
import com.googlecode.adaboost.classifier.util.WeakClassifierEvaluator;
import com.googlecode.adaboost.exception.AdaBoostException;
import com.googlecode.adaboost.trainer.AdaBoostConfiguration;
import com.googlecode.adaboost.trainer.DataElement;
import com.googlecode.adaboost.trainer.TrainingData;

public class RealPointWeakClassifier extends RealWeakClassifier {

	private double value;
	private double epsilon;

	@Override
	public void initalize(AdaBoostConfiguration systemSettings,
			Map<String, String> moduleSettings) throws AdaBoostException {
		epsilon = systemSettings.getEpsilon();
	}

	@Override
	public void initClassifier(TrainingData trainingData, double[] probability) {
		Vector<DataElement> data = trainingData.getTrainingData();
		int num = data.size();
		double bestValue;
		double minG = 0.0;
		double G = 0.0;
		value = data.get(0).getInput().get(0) - 1;
		bestValue = value;
		minG = WeakClassifierEvaluator.evaluateRealClassifier(this,
				trainingData, probability, epsilon);
		for (int i = 0; i < num - 1; ++i) {
			while (i + 1 < num
					&& data.get(i + 1).getInput() == data.get(i).getInput()) {
				i++;
			}
			value = (data.get(i).getInput().get(0) + data.get(i + 1).getInput()
					.get(0)) * 0.5;
			G = WeakClassifierEvaluator.evaluateRealClassifier(this,
					trainingData, probability, epsilon);
			if (G < minG) {
				bestValue = value;
				minG = G;
			}
		}
		value = bestValue;
	}

	@Override
	public int makeDecision(DataElement data) {
		if (data.getInput().get(0) < value) {
			return 1;
		}
		return -1;
	}

	@Override
	public void dumpClassifier() {
		System.out.println("h = I(x < " + value + ")");
		System.out.printf("cplus = %.4f, cpminus = %.4f\n", cplus, cminus);
	}

}
